package com.bstek.uflo.form.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceView;

import com.bstek.dorado.web.resolver.AbstractResolver;
import com.bstek.uflo.command.CommandService;
import com.bstek.uflo.form.command.GetFormCommand;
import com.bstek.uflo.form.model.Form;

/**
 * @author Jacky.gao
 * @since 2013年11月7日
 */
public class DispatchFormPathController extends AbstractResolver {
	private CommandService commandService;
	@Override
	protected ModelAndView doHandleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String uri=request.getRequestURI();
		String id=uri.substring(uri.lastIndexOf('/')+1);
		long formId=0;
		try{
			formId=Long.valueOf(id);
		}catch(NumberFormatException ex){
			throw new IllegalArgumentException("Bad request,"+id+" is not a valid form id.");
		}
		Form form=commandService.executeCommand(new GetFormCommand(formId));
		if(form==null){
			throw new IllegalArgumentException("Form "+formId+" is not exist!");
		}
		long tableId=form.getTableId();
		FormHolder.setForm(form);
		String url="/com.bstek.uflo.form.view.common.CommonPage.d?tableId="+tableId+"";
		ModelAndView modelAndView=new ModelAndView();
		modelAndView.setView(new InternalResourceView(url));
		return modelAndView;
	}
	public CommandService getCommandService() {
		return commandService;
	}
	public void setCommandService(CommandService commandService) {
		this.commandService = commandService;
	}
}
